//
//  MNDReturnListRootViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/6/7.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDReturnListRootViewController.h"
#import "MNDReturnListIndicator.h"
#import "MNDReturnListViewController.h"
#import "MNDReturnListRootContainerViewController.h"
#import "MNDCalendarViewController.h"

@interface MNDReturnListRootViewController () <UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate, UITableViewDelegate>

@property (strong, nonatomic) MNDReturnListIndicator *indicatorContainerView;
//@property (strong, nonatomic) NSArray *segmentButtons;
//@property (nonatomic) CGFloat indicatorLeading;
@property (strong, nonatomic) MNDReturnListRootContainerViewController *pageViewController;
//保存分页的数组
@property (strong, nonatomic) NSMutableArray *pageContentControllers;
//YES表示通过选择按钮切换页面，NO表示通过滑动切换页面
@property (assign, nonatomic) BOOL isManuallSegmentSelect;
@property (assign, nonatomic) BOOL isGotoRighPlace;
@property (assign, nonatomic) BOOL changedController;
@property (assign, nonatomic) BOOL userDraggingStartedTransitionInProgress;

@property (assign, nonatomic) NSInteger currentIndexController;
@property (assign, nonatomic) NSInteger nextIndexController;

@end

@implementation MNDReturnListRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialIndicatorView];
    [self initialPageViewControllers];
    [self initialRightBarButtonItems];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initialIndicatorView {
    self.indicatorContainerView = [[MNDReturnListIndicator alloc] initWithFrame:CGRectMake(0, 0, 180, 44)];
    self.navigationItem.titleView = self.indicatorContainerView;
    //    self.indicatorLeading = self.indicatorContainerView.indicatorSpace;
    
    for (UIButton *button in self.indicatorContainerView.segmentButtons) {
        [button addTarget:self action:@selector(tappSegmentAction:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)initialRightBarButtonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIImage *itemImage = [UIImage imageNamed:@"calendar_icon"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage: itemImage
                                                             style: UIBarButtonItemStylePlain
                                                            target: self
                                                            action: @selector(toCalendarViewControllerAction:)];
    item.tintColor = kColorBackButtonColor;
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)toCalendarViewControllerAction:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"ReturnList" bundle:nil];
    UINavigationController *calendarVC = [storyboard instantiateViewControllerWithIdentifier:@"CalendarNavi"];
    calendarVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:calendarVC animated:YES completion:^{
        
    }];
}

#pragma mark - 配置左右列表

//配置左右切换的列表VC
- (void)initialPageViewControllers {
    //配置所有两个列表的VC
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"ReturnList" bundle:nil];
    MNDReturnListViewController *leftVC = [storyboard instantiateViewControllerWithIdentifier:[MNDReturnListViewController description]];
    leftVC.returnType = ReturnListType_unReturn;
    
    MNDReturnListViewController *rightVC = [storyboard instantiateViewControllerWithIdentifier:[MNDReturnListViewController description]];
    rightVC.returnType = ReturnListType_return;
    
    
    //将controller加入数组中
    [self.pageContentControllers addObject:leftVC];
    [self.pageContentControllers addObject:rightVC];
    
    //把ContainerViewController变成PageViewController
    self.pageViewController = self.childViewControllers[0];
    self.pageViewController.dataSource = self;
    self.pageViewController.delegate = self;
    [self.pageViewController setViewControllers: @[self.pageContentControllers.firstObject]
                   direction: UIPageViewControllerNavigationDirectionForward
                    animated: YES
                  completion: ^(BOOL finished) {
                      
                  }];
    
    for (UIView *subView in self.pageViewController.view.subviews) {
        if ([subView isKindOfClass:[UIScrollView class]]) {
            ((UIScrollView *)subView).delegate = self;
        }
    }
}

#pragma mark - 跳转

#pragma mark - UIPageViewControllerDataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    
    for (NSInteger i = 0; i < self.pageContentControllers.count - 1; i++) {
        if (viewController == [self.pageContentControllers objectAtIndex:i]) {
            return [self.pageContentControllers objectAtIndex:i + 1];
        }
    }
    
    return nil;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    for (NSInteger i = self.pageContentControllers.count - 1; i > 0; i--) {
        if (viewController == [self.pageContentControllers objectAtIndex:i]) {
            
            return [self.pageContentControllers objectAtIndex:i - 1];
        }
    }
    return nil;
}
#pragma mark - UIPageViewControllerDelegate

- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    
    if (pendingViewControllers.count > 0) {
        self.nextIndexController = [self checkIndexOfController:[pendingViewControllers firstObject]];
    }
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed) {
        if (self.nextIndexController != -1) {
            self.currentIndexController = self.nextIndexController;
        }
        self.changedController = YES;
    }
    if (finished) {
        
    }
}

#pragma mark - UIScrollView Delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.isTracking || scrollView.isDecelerating) {
        self.userDraggingStartedTransitionInProgress = YES;
    }
    
    CGPoint point = scrollView.contentOffset;
    
    float percentComplete;
    percentComplete = fabs(point.x - self.view.frame.size.width)/self.view.frame.size.width;
    
    if (self.isManuallSegmentSelect) {
        
        if (percentComplete == 1.0) {
            self.isGotoRighPlace = YES;
            self.indicatorContainerView.indicatorSpace = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.nextIndexController;
        }
        
        if (!self.isGotoRighPlace) {
            NSInteger changeIndex;
            if (self.nextIndexController > self.currentIndexController) {
                changeIndex = self.nextIndexController - self.currentIndexController;
            } else {
                changeIndex = self.currentIndexController - self.nextIndexController;
            }
            
            if (self.nextIndexController > self.currentIndexController || self.nextIndexController == self.pageContentControllers.count - 1) {
                self.indicatorContainerView.indicatorSpace = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete * changeIndex  + self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController;
            } else {
                self.indicatorContainerView.indicatorSpace = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController - self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete * changeIndex;
            }
        }
        
    } else {
        CGFloat widthSegment = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count;
        
        if (percentComplete * widthSegment > widthSegment / 2) {
            [self changeSelectedButtonToIndex:self.nextIndexController];
        }
        
        if (self.changedController) {
            self.indicatorContainerView.indicatorSpace = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController;
            self.changedController = NO;
        } else  {
            if (self.nextIndexController > self.currentIndexController || self.nextIndexController == self.pageContentControllers.count - 1) {
                self.indicatorContainerView.indicatorSpace = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete + self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController;
            } else {
                self.indicatorContainerView.indicatorSpace = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController - self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete;
            }
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.userDraggingStartedTransitionInProgress = NO;
}

#pragma mark - Action
//需要在storyboard设置button的tag值，或者在viewDidLoad设置
- (IBAction)tappSegmentAction:(UIButton *)sender {
    NSInteger index = sender.tag % 100;
    if (self.currentIndexController == index) {
        return;
    }
    
    if (self.userDraggingStartedTransitionInProgress) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    UIPageViewControllerNavigationDirection direction;
    if (index > self.currentIndexController) {
        direction = UIPageViewControllerNavigationDirectionForward;
    }else{
        direction = UIPageViewControllerNavigationDirectionReverse;
    }
    
    self.isManuallSegmentSelect = YES;
    self.nextIndexController = index;
    
    id controller = self.pageContentControllers[index];
    NSArray *viewControllers = @[controller];
    [self.pageViewController setViewControllers:viewControllers direction:direction animated:YES completion:^(BOOL finished) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.currentIndexController = weakSelf.nextIndexController;
            [weakSelf changeSelectedButtonToIndex:weakSelf.currentIndexController];
            weakSelf.isGotoRighPlace = NO;
            weakSelf.isManuallSegmentSelect = NO;
        });
    }];
}

#pragma mark - Utility

- (NSInteger)checkIndexOfController:(UIViewController *)controller  {
    for (NSInteger i = 0; i < self.pageContentControllers.count; i++) {
        if (controller == [self.pageContentControllers objectAtIndex:i]) {
            return i;
        }
    }
    
    return -1;
}

- (void)changeSelectedButtonToIndex:(NSInteger)index {
    for (UIButton *button in self.indicatorContainerView.segmentButtons) {
        if (button == [self.indicatorContainerView.segmentButtons objectAtIndex:index]) {
            [button setSelected:YES];
        } else {
            [button setSelected:NO];
        }
    }
}

#pragma mark - gettter

- (NSMutableArray *)pageContentControllers {
    if (!_pageContentControllers) {
        _pageContentControllers = [NSMutableArray array];
    }
    
    return _pageContentControllers;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
